package com.cqie.tes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqie.tes.comm.TR;
import com.cqie.tes.config.MyUserDetile;
import com.cqie.tes.domain.SysUser;
import com.cqie.tes.utils.EncryptUtil;
import com.cqie.tes.domain.RoleUser;
import com.cqie.tes.domain.SysRole;
import com.cqie.tes.domain.po.SysUserPo;
import com.cqie.tes.domain.qo.SysUserQo;
import com.cqie.tes.comm.R;
import com.cqie.tes.domain.vo.SysUserVo;
import com.cqie.tes.service.RoleUserService;
import com.cqie.tes.service.SysRoleService;
import com.cqie.tes.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@CrossOrigin
@RestController
@Api(tags = "用户管理")
@RequestMapping("/sysuser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private SysRoleService sysRoleService;

    // 根据id查询
    @ApiOperation("根据id查询")
    @GetMapping("{id}")
    public R getSysUserById(
            @ApiParam(name = "id", value = "用户id", required = true) @PathVariable Integer id
    ) {
        if (id == null) {
            return R.error().message("id不能为空");
        }
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            return R.error().message("用户不存在:" + id);
        }
        // 获取角色信息
        SysUserPo sysUserPo = new SysUserPo();
        // 1.复制mo-po
        BeanUtils.copyProperties(sysUser, sysUserPo);
        // 2.查询角色信息
        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("userId", id);
        List<RoleUser> roleUserList = roleUserService.list(roleUserQueryWrapper);
        // 3.对po赋值
        List<Long> roleIdList = new ArrayList<>();
        for (RoleUser roleUser : roleUserList
        ) {
            roleIdList.add(roleUser.getRoleId());
        }
        sysUserPo.setRoleIdList(roleIdList);
        // 4.返回信息
        return R.ok().data("user", sysUserPo);
    }

    //
    @ApiOperation("查看用户详情")
    @GetMapping("/details/{id}")
    public R details(
            @ApiParam(name = "id", value = "用户ID", required = true) @PathVariable Long id
    ) {
        if (id == null) {
            return R.error().message("id不能为空");
        }
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            return R.error().message("用户不存在:" + id);
        }
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(sysUser, sysUserVo);
        sysUserVo.setStatusName(sysUserVo.getStatus() == 0 ? "正常" : "禁用");

        // 2.查询角色信息
        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("userId", id);
        List<RoleUser> roleUserList = roleUserService.list(roleUserQueryWrapper);
        // 3.对po赋值
        List<Long> roleIdList = new ArrayList<>();
        for (RoleUser roleUser : roleUserList
        ) {
            roleIdList.add(roleUser.getRoleId());
        }
        sysUserVo.setRoleIdList(roleIdList);

        return R.ok().data("user", sysUserVo);
    }


    // 分页查询
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public R pageListSysUser(
            @ApiParam(name = "page", value = "当前页", required = true) long page,
            @ApiParam(name = "limit", value = "每页条数", required = true) long limit
    ) {
//        System.out.println(page+" "+limit);

        // 创建page对象
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        sysUserService.page(sysUserPage, null);
        // 开始查询
        IPage<SysUser> sysUserIPage = sysUserService.page(sysUserPage, null);
        // 获取数据
        List<SysUser> sysUserList = sysUserIPage.getRecords();
        // 封装vo
        List<SysUserVo> sysUserVos = new ArrayList<>();
        for (int i = 0; i < sysUserList.size(); i++) {
            // 封装状态信息
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUserList.get(i), sysUserVo);
            sysUserVo.setStatusName(sysUserList.get(i).getStatus() == 0 ? "正常" : "禁用");
            // 封装角色信息
            // 查询该用户所有角色
            QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
            roleUserQueryWrapper.eq("userId", sysUserVo.getId());
            List<RoleUser> roleUserList = roleUserService.list(roleUserQueryWrapper);
            // 根据roleId查询名称
            List<SysRole> roleList = new ArrayList<>();
            // 用戶角色列表
            for (RoleUser r : roleUserList
            ) {
                // 根據角色id查詢角色
                QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
                sysRoleQueryWrapper.eq("id", r.getRoleId());
                List<SysRole> sysRoleList = sysRoleService.list(sysRoleQueryWrapper);
                for (SysRole sr : sysRoleList
                ) {
//                    System.out.println(sr.getName());
                    if (!roleList.contains(sr)) {
                        roleList.add(sr);
                    }
                }
            }
            sysUserVo.setRoleIdList(sysUserService.getRoleIdBySysUserId(sysUserVo.getId()));
            sysUserVo.setRoleList(roleList);
            // 加入数据列表
            sysUserVos.add(sysUserVo);
        }
        // 总数据数
        Long total = sysUserIPage.getTotal();

        return R.ok().data("total", total).data("rows", sysUserVos);

    }

    // 条件查询
    @PostMapping("/condition")
    public R condition(
            @ApiParam(name = "sysUserQo", value = "条件对象", required = true) @RequestBody(required = false) SysUserQo sysUserQo
    ) {
        // 构建条件对象
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        String name = sysUserQo.getName();
        if (!StringUtils.isEmpty(name)) {
            sysUserQueryWrapper.like("name", name);
        }
        List<SysUser> sysUserList = sysUserService.list(sysUserQueryWrapper);

        // 封装vo
        List<SysUserVo> sysUserVos = new ArrayList<>();
        for (int i = 0; i < sysUserList.size(); i++) {
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUserList.get(i), sysUserVo);
            sysUserVo.setStatusName(sysUserList.get(i).getStatus() == 0 ? "正常" : "禁用");
            sysUserVos.add(sysUserVo);
        }
        // 总数据数
        int total = sysUserList.size();

        return R.ok().data("total", total).data("rows", sysUserVos);

    }

    // 条件查询带分页
    @ApiOperation("条件查询带分页")
    @PostMapping("/pageContion")
    public R pageListSysUserCondition(
            @ApiParam(name = "page", value = "当前页", required = true) long page,
            @ApiParam(name = "limit", value = "每页条数", required = true) long limit,
            @ApiParam(name = "sysUserQo", value = "条件对象", required = true) @RequestBody(required = false) SysUserQo sysUserQo
    ) {
        // 构建条件对象
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        String name = sysUserQo.getName();
        if (!StringUtils.isEmpty(name)) {
            sysUserQueryWrapper.like("name", name);
        }
        // 创建page对象
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        // 开始查询
        IPage<SysUser> sysUserIPage = sysUserService.page(sysUserPage, sysUserQueryWrapper);
        // 获取数据
        List<SysUser> sysUserList = sysUserIPage.getRecords();
        // 封装vo
        List<SysUserVo> sysUserVos = new ArrayList<>();
        for (int i = 0; i < sysUserList.size(); i++) {
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUserList.get(i), sysUserVo);
            sysUserVo.setStatusName(sysUserList.get(i).getStatus() == 0 ? "正常" : "禁用");
            sysUserVos.add(sysUserVo);
        }
        // 总数据数
        Long total = sysUserIPage.getTotal();

        return R.ok().data("total", total).data("rows", sysUserVos);

    }

    // TODO 逻辑删除没有体现
    // 增加修改
    @ApiOperation("增加修改")
    @GetMapping("/role")
    public R beforAdd() {
        return R.ok().data("roleList", sysRoleService.list());
    }

    //    @GetMapping(/)
//    public R beforeModify(){
//
//        return R.ok();
//    }
    @ApiOperation("增加修改")
    @PostMapping("/saveOrUpdate")
    public R saveOrUpdate(
            @ApiParam(name = "sysUser", value = "用户对象", required = true) @RequestBody SysUserPo sysUserPo
    ) {
        try {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserPo, sysUser);
            // 加密 有id说明是更新，密码不动
            // TODO 加一個數據庫判斷
            System.out.println("1");
            if (sysUserPo.getId() == null) {
//                System.out.println("密码加密："+sysUserPo.getId());
                sysUserPo.setPassword(EncryptUtil.getInstance().MD5(sysUserPo.getPassword()));
            }
            // 存用户表
            System.out.println(2);
            sysUserService.saveOrUpdate(sysUserPo); // 有id修改，沒有id保存
            // 保存关系
            List<RoleUser> roleUserList = new ArrayList<>();
            // 这里可能为空，如果为空则要判断
            if (sysUserPo.getRoleIdList() == null) {
                sysUserPo.setRoleIdList(new ArrayList<Long>());
            }
            if (sysUserPo.getRole() != null) {
                sysUserPo.getRoleIdList().add(sysUserPo.getRole());
            }

            // 删除角色信息
            sysUserService.deleteRoleUserBySysUserId(sysUserPo.getId());


            for (Long roleId : sysUserPo.getRoleIdList()
            ) {
                RoleUser roleUser = new RoleUser();
                roleUser.setUserId(sysUserPo.getId());
                roleUser.setRoleId(roleId);
                System.out.println("userid-" + sysUserPo.getId() + "-" + roleId);
                roleUserList.add(roleUser);
//                roleUserService.save(roleUser);
            }
            // 批量保存
//            System.out.println("roleUserList->size:" + roleUserList.size());
            roleUserService.saveBatch(roleUserList);
//            System.out.println(sysUserPo);
//            sysUserPo.setId(sysUserPo.getId());
            // po -> vo
        } catch (Exception e) {
            System.out.println("异常");
            return R.error().message(e.getMessage());
        }

        return R.ok().data("user", sysUserPo);
    }


    // TODO 有错 415
    // 删除
    @PostMapping("/delete")
    public R deleteSysUserById(
            @ApiParam(name = "ids[]", value = "用户id列表", required = true) @RequestParam("ids[]") List<Long> ids
    ) {



        try {
            for (Long id:ids
                 ) {
                System.out.println("id:"+id);
                List<SysUser> sysUserList;
                if (true){
                    QueryWrapper<SysUser> qw = new QueryWrapper<>();
                    qw.eq("id",id);
                    sysUserList = sysUserService.list(qw);
                }
                if (sysUserList.isEmpty()){
                    return R.error().message("用户不存在");
                }
                sysUserService.deleteRoleUserBySysUserId(id);
                sysUserService.removeById(id);
            }
            return R.ok();
        } catch (Exception e) {
            return R.error().message(e.getMessage());
        }
    }

    // 修改
    @PostMapping("/updateSysUser")
    public R updateSysUser(
            @ApiParam(name = "sysUser", value = "用户对象", required = true) @RequestBody SysUser sysUser
    ) {
        boolean state = sysUserService.updateById(sysUser);
        if (state) {
            return R.ok();
        }
        return R.error();
    }

    @GetMapping("info")
    public TR info(){
        MyUserDetile principal = (MyUserDetile) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null){
            return TR.ok().data(new SysUser());
        }
        SysUser user = sysUserService.getById(principal.getSysUser().getId());
        return TR.ok().data(user);
    }



    @PostMapping("/optionlist")
    public R optionList(){
        return sysUserService.optionList();
    }


}
